package hg.demo.mybatis.plus.chatgpt;

import javax.swing.table.AbstractTableModel;
import java.util.ArrayList;
import java.util.List;

public class StudentTableModel extends AbstractTableModel {
    private static final String[] COLUMN_NAMES = {"学号", "姓名", "性别", "年龄", "专业"};
    private static final Class[] COLUMN_TYPES = {Integer.class, String.class, String.class, Integer.class, String.class};

    private List<Student> students;

    public StudentTableModel() {
        students = new ArrayList<>();
    }

    public StudentTableModel(List<Student> students) {
        this.students = students;
    }

    @Override
    public int getRowCount() {
        return students.size();
    }

    @Override
    public int getColumnCount() {
        return COLUMN_NAMES.length;
    }

    @Override
    public String getColumnName(int columnIndex) {
        return COLUMN_NAMES[columnIndex];
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        return COLUMN_TYPES[columnIndex];
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Student student = students.get(rowIndex);
        if (columnIndex == 0) {
            return student.getId();
        } else if (columnIndex == 1) {
            return student.getName();
        } else if (columnIndex == 2) {
            return student.getGender();
        } else if (columnIndex == 3) {
            return student.getAge();
        } else if (columnIndex == 4) {
            return student.getMajor();
        }
        return null;
    }

    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        Student student = students.get(rowIndex);
        if (columnIndex == 0) {
            student.setId((Integer) aValue);
        } else if (columnIndex == 1) {
            student.setName((String) aValue);
        } else if (columnIndex == 2) {
            student.setGender((String) aValue);
        } else if (columnIndex == 3) {
            student.setAge((Integer) aValue);
        } else if (columnIndex == 4) {
            student.setMajor((String) aValue);
        }
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return true;
    }

    public void addStudent(Student student) {
        students.add(student);
        fireTableRowsInserted(students.size() - 1, students.size() - 1);
    }

    public void updateStudent(Student student) {
        int index = students.indexOf(student);
        students.set(index, student);
        fireTableRowsUpdated(index, index);
    }

    public void deleteStudent(int rowIndex) {
        students.remove(rowIndex);
        fireTableRowsDeleted(rowIndex, rowIndex);
    }

    public List<Student> getStudents() {
        return students;
    }

    public void setStudents(List<Student> students) {
        this.students = students;
    }
}
